<script setup>
import TableBase from '@/components/Table-Base.vue'
import TablePagination from '@/components/Table-Pagination.vue'
import DialogBase from '@/components/Dialog-Base.vue'
import { ref } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { addAreaItem, getAreaList, editAreaItem, delAreaItem, getAreaItem } from '@/api/area'
import { getAllRulesList } from '@/api/rules'
import MainContent from '@/components/Main-Content.vue'

const showDialog = ref(false)
const dialogType = ref('add')
const rules = ref({
    areaName: [
        { required: true, message: '请输入区域名称', trigger: 'blur' },
        { min: 2, max: 16, message: '长度在 2 到 16 个字符', trigger: 'blur' }
    ],
    spaceNumber: [
        { required: true, message: '请输入车位数', trigger: 'blur' },
        { min: 1, message: '楼宇层数最少为 1', trigger: 'blur' }
    ],
    areaProportion: [
        { required: true, message: '请输入区域面积', trigger: 'blur' },
        { min: 1, message: '在管面积最少为 1', trigger: 'blur' }
    ],
    ruleId: [
        { required: true, message: '请选择计费规则', trigger: 'change' }
    ]
})
const dialogForm = ref({})
const query = ref({
    page: 1,
    pageSize: 10
})
const listData = ref({
    list: [],
    total: 0
})
const rulesList = ref([])
const columns = ref([
    {
        title: '序号',
        colKey: 'serial-number',
        width: 80
    },
    {
        title: '区域名称',
        colKey: 'areaName'
    },
    {
        title: '车位数（个）',
        colKey: 'spaceNumber'
    },
    {
        title: '区域面积（㎡）',
        colKey: 'areaProportion'
    },
    {
        title: '计费规则',
        colKey: 'ruleName'
    },
    {
        title: '备注',
        colKey: 'remark'
    },
    {
        title: '操作',
        colKey: 'option'
    }
])
const dialogFormInstance = ref(null)

const search = async () => {
    const res = await getAreaList({ ...query.value, })
    listData.value.list = res.data.rows
    listData.value.total = res.data.total
}
const getRules = async () => {
    rulesList.value = (await getAllRulesList()).data.rows
}
const addArea = () => {
    dialogType.value = 'add'
    showDialog.value = true
    getRules()
}
const closeDialog = () => {
    showDialog.value = false
    dialogFormInstance.value.clearValidate()
}
const clickClose = () => {
    showDialog.value = false
    dialogFormInstance.value.reset()
    dialogForm.value = {}
}
const dialogConfirm = async () => {
    const valid = await dialogFormInstance.value.validate()
    if (typeof valid === 'boolean' && valid) {
        if (dialogType.value === 'add') {
            const res = await addAreaItem(dialogForm.value)
            if (res.code !== 10000) return
            closeDialog()
            dialogFormInstance.value.reset()
            await MessagePlugin.success('添加成功！')
            await search()
        } else {
            const res = await editAreaItem({
                id: dialogForm.value.id,
                areaName: dialogForm.value.areaName,
                spaceNumber: dialogForm.value.spaceNumber,
                areaProportion: dialogForm.value.areaProportion,
                remark: dialogForm.value.remark,
                ruleId: dialogForm.value.ruleId
            })
            if (res.code !== 10000) return
            closeDialog()
            await MessagePlugin.success('修改成功！')
            await search()
        }
    }
}
const getRow = async (data, type) => {
    if (type === 'edit') {
        dialogType.value = 'edit'
        showDialog.value = true
        await getRules()
        let res = {}
        try {
            res = await getAreaItem(data.row.id)
        } catch (error) {
            console.error(error.response.data.msg)
        }
        if (res.code === 10000) {
            dialogForm.value = res.data
        } else {
            dialogForm.value = JSON.parse(JSON.stringify(listData.value.list.find(e => e.id === data.row.id)))
        }
    } else {
        const res = await delAreaItem(data.row.id)
        if (res.code === 10000) {
            await MessagePlugin.success('删除成功!')
            if (listData.value.list.length === 1 && query.value.page > 1) query.value.page--
            await search()
        } else {
            await MessagePlugin.error(res.msg)
        }
    }
}
const changePage = e => {
    query.value.page = e.current
    query.value.pageSize = e.pageSize
    search()
}

search()
</script>

<template>
    <main-content>
        <table-base :columns="columns" :list="listData.list">
            <template #top-btn>
                <t-button theme="primary" @click="addArea">添加区域</t-button>
            </template>
            <template #option-table="row">
                <t-button variant="text" theme="primary" @click="getRow(row, 'edit')">编辑</t-button>
                <t-popconfirm
                    destroyOnClose
                    showArrow
                    @confirm="getRow(row, 'del')"
                    theme="warning" content="确认删除吗">
                    <t-button variant="text" theme="primary">删除</t-button>
                </t-popconfirm>
            </template>
        </table-base>

        <table-pagination :total="listData.total" @changePage="changePage"></table-pagination>

        <dialog-base :showDialog="showDialog"
                     :dialogType="dialogType"
                     :dialogTitle="dialogType === 'add' ? '添加区域' : '编辑区域'"
                     @dialogConfirm="dialogConfirm"
                     @clickClose="clickClose"
                     @closeDialog="closeDialog">
            <t-form class="dialogForm" ref="dialogFormInstance" labelAlign="top" :rules="rules" :data="dialogForm">
                <t-form-item label="区域名称" name="areaName">
                    <t-input placeholder="请输入区域名称" v-model.trim="dialogForm.areaName"/>
                </t-form-item>
                <t-form-item label="车位数" name="spaceNumber">
                    <t-input-adornment append="个">
                        <t-input-number placeholder="请输入车位数"
                                        v-model.trim="dialogForm.spaceNumber"
                                        theme="column" min="1" max="1000000000" :allowInputOverLimit="false"/>
                    </t-input-adornment>
                </t-form-item>
                <t-form-item label="区域面积" name="areaProportion">
                    <t-input-adornment append="㎡">
                        <t-input-number placeholder="请输入区域面积"
                                        v-model.trim="dialogForm.areaProportion"
                                        theme="column" min="1" max="1000000000" :allowInputOverLimit="false"/>
                    </t-input-adornment>
                </t-form-item>
                <t-form-item label="关联计费规则" name="ruleId">
                    <t-select
                        filterable
                        showArrow
                        v-model.trim="dialogForm.ruleId">
                        <t-option v-for="e in rulesList" :key="e.id" :label="e.ruleName" :value="e.id" />
                    </t-select>
                </t-form-item>
                <t-form-item label="备注" name="remark">
                    <t-textarea placeholder="请输入备注" v-model.trim="dialogForm.remark"/>
                </t-form-item>
            </t-form>
        </dialog-base>
    </main-content>
</template>

<style scoped lang="scss">
.btn-group {
    button:first-child {
        margin-right: 10px;
    }
}

.dialogForm {
    :deep .t-form__controls-content {
        .t-input-number {
            flex: 1;
            width: initial;
        }

        .t-input-adornment {
            flex: 1;

            .t-input-number {
                flex: 1;
                width: auto;
            }
        }
    }

    :deep .t-form-item__propertyFeePrice {
        .t-input-adornment__text {
            width: 52px;
        }
    }
}
</style>
